package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseOrderSaleDetailFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.OderSaleContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("deprecation") public class AddOrderSaleFragment
    extends BaseOrderSaleDetailFragment {

  private CurrentUser mCurrentUser;
  private String id = "";
  private String moutkindCode = "";
  private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
  private OderSaleContent mContent = new OderSaleContent();
  private CallBack mcallBack;
  public static boolean isSave = false;//主表时不是保存成功

  //回调接口
  public interface CallBack {
    void onRefresh(OderSaleContent morderContent);
  }

  @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mcallBack = (CallBack) getActivity();
  }

  @Override public void onDetach() {
    super.onDetach();
    mcallBack = null;
  }

  @Override protected void setTitle() {
    setTitleCustom(R.string.order_detail);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mCurrentUser = CurrentUser.newInstance(getActivity());
    moutkindCode = mCurrentUser.getMemberCode() + "-DJLB-OUT-XSDDCK";
    salePersonId = mCurrentUser.getJobNumber();
    id = UUID.randomUUID().toString();
    AddOrderSaleFragment.isSave = false;

    super.onCreate(savedInstanceState);
  }

  //获取单据编号
  private void volleyGetCode() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ORDER_CODE);
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("ruleFlag", "outReceiptsRecordCode");
    params.put("certificateCode", moutkindCode);

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            //获取单据编号成功
            tvOutNotes.setText(success.getMessage());
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override protected void initOrderData() {
    tvRegisteredErson.setText(mCurrentUser.getRealName());
    tvRegisteredTime.setText(format.format(new Date()));
    tvSalePerson.setText(mCurrentUser.getRealName());
    llGone.setVisibility(View.GONE);//办理时间
    //获取销售订单编号
    volleyGetCode();

    //		llDataStatus.setVisibility(View.GONE);//数据状态
    //		llHandlePrson.setVisibility(View.GONE);//办理人
    //		llHandleTime.setVisibility(View.GONE);//办理时间

    //		llGone.setVisibility(View.GONE);//办理时间
    //		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //		tvRegisteredErson.setText(mCurrentUser.getRealName());
    //		tvRegisteredTime.setText(format.format(new Date()));

  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    //		inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      //		case android.R.id.home:
      //			if (NavUtils.getParentActivityName(getActivity())!=null) {
      //				NavUtils.navigateUpFromSameTask(getActivity());
      //			}
      //			break;

      //保存订单方法
      case R.id.menu_item_save:
        if (!isSave) {
          if (TextUtils.isEmpty(tvOutNotes.getText().toString())) {
            Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
          } else if (TextUtils.isEmpty(tvWarehouse.getText().toString())) {
            ToastUtil.show(R.string.first_storage);
          } else {
            //				volleyPoastSave();
            showDialog(SAVE_ORDER);
          }
        } else {
          ToastUtil.show(R.string.is_save);
        }

        break;

      //保存并启动流程
      case R.id.menu_item_submit:
        if (!isSave) {
          if (TextUtils.isEmpty(tvOutNotes.getText().toString())) {
            Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
          } else if (TextUtils.isEmpty(tvWarehouse.getText().toString())) {
            ToastUtil.show(R.string.first_storage);
          } else {
            showDialog(SAVE_START);
          }
        } else {
          ToastUtil.show(R.string.is_save);
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //保存订单方法
  private void volleyPoastSave(final int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SAVE_ORDER);
    HashMap<String, String> params = new HashMap<>();
    /**
     * 默认值
     * id : uuid
     * memberCode  :会员编码
     * moutappDate : 当前时间(yyyy-MM-dd),
     * moutkindCode : memberCode + '-DJLB-OUT-XSDDCK'(固定值)
     *
     sumPrice : (计算合计金额),
     sumPriceString : (合计金额大写)，
     isOutAll : 'F'(固定值)
     */
    params.put("id", id);
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("moutappDate", format.format(new Date()));
    params.put("moutkindCode", moutkindCode);
    params.put("sumPrice", "0");
    params.put("sumPriceString", "零");
    params.put("isOutAll", "F");

    params.put("mcustomerName", tvCustomerCompany.getText().toString());
    params.put("mcustomerId", customerId);

    params.put("mcustomerDeptName", etCustomerApartment.getText().toString());
    params.put("moutCom", etMainProduct.getText().toString());

    params.put("materialKindCode", materialKindCode);
    params.put("materialKindName", materialKindName);

    params.put("storageName", tvWarehouse.getText().toString());
    params.put("storageId", warehouseId);

    params.put("moutappmanName", tvSalePerson.getText().toString());
    params.put("moutappmanId", salePersonId);

    params.put("moutbillNo", tvOutNotes.getText().toString());
    params.put("regStaffName", tvRegisteredErson.getText().toString());
    params.put("regStaffId", mCurrentUser.getJobNumber());
    params.put("regDate", tvRegisteredTime.getText().toString());
    params.put("moutbillStatus", "new");
    params.put("remark", etNotes.getText().toString());

    HashMap<String, String> mparams = new HashMap<>();
    mparams.put("inserted", "[" + new JSONObject(params).toString() + "]");
    LogUtil.i("添加参数mparams====" + mparams.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mparams, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);

              isSave = true;
              //发送广播,
              setOrderContent();
              //发送完广播跳转到物料列表界面
              mcallBack.onRefresh(mContent);
              //保存后主表不可编辑
              ibCustomerCompany.setVisibility(View.GONE);
              ibSalePerson.setVisibility(View.GONE);
              ibWarehouse.setVisibility(View.GONE);
              etCustomerApartment.setEnabled(false);
              etMainProduct.setEnabled(false);
              etNotes.setEnabled(false);
            } else if (SAVE_START == requestCode) {
              //启动流程
              volleyPostSubmit();
            }
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      private void setOrderContent() {
        mContent.setId(id);
        mContent.setMcustomerName(tvCustomerCompany.getText().toString());
        mContent.setMcustomerId(customerId);

        mContent.setMaterialKindCode(materialKindCode);
        mContent.setMaterialKindName(tvMaterialKind.getText().toString());

        mContent.setMcustomerDeptName(etCustomerApartment.getText().toString());
        mContent.setMoutCom(etMainProduct.getText().toString());

        mContent.setStorageName(tvWarehouse.getText().toString());
        mContent.setStorageId(warehouseId);

        mContent.setMoutappmanName(tvSalePerson.getText().toString());
        mContent.setMoutappmanId(salePersonId);
        mContent.setRemark(etNotes.getText().toString());

        mContent.setMoutbillStatus("new");

        //				//发送广播
        //				Intent broad=new Intent(ACTION_SHOW_NOTIFICATION);
        //				broad.putExtra(AddMaterielListFragment.EXTRA_CONTENT, mContent);
        //				getActivity().sendBroadcast(broad,PERM_PRIVATE);
        //				LogUtil.i("发送广播=====");

      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  // 启动流程
  private void volleyPostSubmit() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SUBMIT_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("ifSaleOrder", "true");
    params.put("id", id);
    LogUtil.i("启动流程===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, volleyResponse());
  }

  public VolleyResponse volleyResponse() {
    return new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == SAVE_ORDER) {
      volleyPoastSave(SAVE);
    }
    if (requestCode == SAVE_START) {
      volleyPoastSave(SAVE_START);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
